<?php

namespace App\Domain\Permissions\Services;

use App\Domain\Permissions\Dao\PermissionsDao;
use App\Domain\Role\Dao\RoleDao;
use App\Exceptions\BadRequestException;
use Illuminate\Support\Facades\Cache;

class PermissionsService
{
    /**
     * 获取用户菜单权限
     * @param $params
     * @return array
     */
    public function getPermissionMenu($params)
    {
        if (isset($params['roleId'])) {
//            $roleIds = explode_no_empty(',', $params['roleId']);
            $roleModel = (new RoleDao)->findById($params['roleId']);
//            dd($roleModel['id']);
            $roleIds = [$roleModel['id']];
//            dd($roleIds);
        } else {
//            $roleModel = auth()->user()->roleModel;
            $roleIds = auth()->user()->roleModel->pluck('id')->toArray();
        }
//        if ($roleModel == null) {
//            throw new \Exception('角色不存在');
//        }
        $dao = new PermissionsDao();
//        $tree = $this->getPermissionMenuCache($params['type']);
        //获取所有tree，因为要根据最底层权限来自动给上级增加权限
        switch ($params['type']) {
            case '1':
                $typeList = [1];
                break;
            case '2':
                $typeList = [1, 2];
                break;
            default:
                throw new BadRequestException('类型不存在');
        }
        $tree = $this->getPermissionMenuCache(2);
        $hasAllAuthority = true;

        $permissionList = (new RoleDao)->getPermissionModelByRoleIds($roleIds)->pluck('id')->toArray();
        $list = $dao->setHasAuthorityAndFilterType($permissionList, $tree, 'authorityList', $typeList, $hasAllAuthority);
        return [
            'list' => $list,
            'hasAllAuthority' => $hasAllAuthority == true ? 1 : 0,
        ];
    }

    /**
     * 从缓存获取权限菜单
     * @param $type 1 菜单  2 菜单和按钮
     * @param bool $refreshCache
     * @return array
     */
    public function getPermissionMenuCache($type, $refreshCache = false)
    {

        switch ($type) {
            case '1':
                $typeList = [1];
                break;
            case '2':
                $typeList = [1, 2];
                break;
            default:
                throw new BadRequestException('类型不存在');
        }
        $tree = Cache::get('getPermissionMenu_' . $type);
        if ($refreshCache || $tree == null) {
            $tree = (new PermissionsDao())->getTree(['*'], $typeList, 'authorityList', false, 'pc');
            Cache::forever('getPermissionMenu_' . $type, $tree);
        }
        return $tree;
    }

    /**
     * 获取权限树
     * @param $appName
     * @return array
     */
    public function getPermissionTree($appName)
    {
        return $this->getPermissionTreeCache(false, $appName);
    }

    /**
     * 从缓存获取权限树
     * @param bool $refreshCache
     * @param string $appName
     * @return array
     */
    public function getPermissionTreeCache($refreshCache = false, $appName = 'pc')
    {
        $tree = Cache::get('permissionTreeCache_' . $appName);
        if ($refreshCache || $tree == null) {
            $tree = (new PermissionsDao)->getTree(['id', 'label as label', 'lvl as level'], [1], 'children', true, $appName);
            Cache::forever('permissionTreeCache_' . $appName, $tree);
        }
        return $tree;
    }

    public function getSelectPermissionByType(string $type)
    {
        $appName = $type == 1 ? "pc" : "pad";
        $permissionName = $appName == "pc" ? "UserBase filing" : "PadUserBaseView";
        $has = (new PermissionsDao)->getPermissionByName($permissionName);
        if (!$has) {
            throw new BadRequestException("权限不存在");
        }
        return $has->id;
    }

    public function getJurisdictionName2JurisdictionIdMap(string $type)
    {
        $res = [];
        $appName = $type == 1 ? "pc" : "pad";
        $list = (new PermissionsDao)->getPermissionByAppName($appName);
        foreach ($list as $v) {
            $res[$v->name] = $v->id;
        }
        return $res;
    }
}
